package com.atguigu.eud_teacher.service.impl;

import com.atguigu.commonutils.exceptionhandler.GuliException;
import com.atguigu.eud_teacher.dao.ChapterDao;
import com.atguigu.eud_teacher.dao.VideoDao;
import com.atguigu.eud_teacher.entity.ChapterEntity;
import com.atguigu.eud_teacher.entity.VideoEntity;
import com.atguigu.eud_teacher.service.ChapterService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.util.List;


@Service("chapterService")
public class ChapterServiceImpl extends ServiceImpl<ChapterDao, ChapterEntity> implements ChapterService {

    @Resource
    private VideoDao videoDao;


    @Override
    //从课程基础信息页面跳到章节页面，获取courseid查询所有章节小节
    public List<ChapterEntity> findAllChaptersAndVideos(String courseId) {
        List<ChapterEntity> chapterEntityList = baseMapper.selectList(new QueryWrapper<ChapterEntity>().eq("course_id", courseId));
        List<VideoEntity> videoEntityList = videoDao.selectList(new QueryWrapper<VideoEntity>().eq("course_id", courseId).orderByAsc("sort"));
        for (ChapterEntity chapter : chapterEntityList) {
            for (VideoEntity video : videoEntityList) {
                if (video.getChapterId().equals(chapter.getId())) {
                    chapter.getVideoEntityList().add(video);
                }
            }
        }
        return chapterEntityList;
    }

    @Override
    //删除章节
    public void removeChapterAndVideo(String id) {
        int count = videoDao.selectCount(new QueryWrapper<VideoEntity>().eq("chapter_id", id));
        VideoEntity v = new VideoEntity();
        if (count > 0) {
            throw new GuliException(20001, "请先删除小节再删除章节");
        }
        baseMapper.deleteById(id);
    }

    @Override
    public void removeChapterByCourseId(String courseId) {
        QueryWrapper<ChapterEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_id", courseId);
        baseMapper.delete(queryWrapper);
    }

}